package labox.innovation.gameserver.model;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javolution.util.FastMap;

import labox.innovation.config.Config;
import labox.innovation.gameserver.model.actor.instance.FuzePcInstance;

/**
 * This class ...
 * 
 * @author Nightmare
 * @version $Revision: 1.5.2.6.2.7 $ $Date: 2005/03/27 15:29:18 $
 */
public final class SpawnTable {

	private static final Logger _log = LoggerFactory.getLogger(SpawnTable.class.getName());

	private Map<Integer, L2Spawn> _spawntable = new FastMap<Integer, L2Spawn>();

	private Scene scn;

	public SpawnTable() {
	}

	public Map<Integer, L2Spawn> getSpawnTable() {
		return _spawntable;
	}

	public static final SpawnTable fromXML(Scene scn, Element e) {
		SpawnTable st = new SpawnTable();
		st.scn = scn;
		try {
			NodeList nl = e.getElementsByTagName("spawn");
			for (int i = -1; ++i < nl.getLength();) {
				L2Spawn spawn = L2Spawn.fromXML((Element) nl.item(i), scn.get_id(), i);
				st._spawntable.put(i, spawn);
				spawn.init();
			}
		} catch (Exception ex) {
			// problem with initializing spawn, go to next one
			_log.error("SpawnTable: Spawn could not be initialized: ", Config.SERVER_ID, e);
		}

		if (_log.isDebugEnabled())
			_log.debug("SpawnTable: Loaded " + st._spawntable.size() + " Npc Spawn Locations.");

		return st;
	}

	public L2Spawn getTemplate(int id) {
		return _spawntable.get(id);
	}

	public void addNewSpawn(L2Spawn spawn) {
		spawn.setId(_spawntable.size());
		_spawntable.put(spawn.getId(), spawn);
	}

	public void deleteSpawn(L2Spawn spawn) {
		if (_spawntable.remove(spawn.getId()) == null)
			return;
	}

	/**
	 * Get all the spawn of a NPC<BR>
	 * <BR>
	 * 
	 * @param npcId
	 *            : ID of the NPC to find.
	 * @return
	 */
	public void findNPCInstances(FuzePcInstance activeChar, int npcId, int teleportIndex) {
		int index = 0;
		for (L2Spawn spawn : _spawntable.values()) {
			if (npcId == spawn.getNpcid()) {
				index++;
				if (teleportIndex > -1) {
					if (teleportIndex == index)
						activeChar.teleToLocation(spawn.getLocation(), spawn.getLocx(), spawn.getLocy());
				} else {
					activeChar.sendMessage(index + " - " + spawn.getTemplate().name + " (" + spawn.getId() + "): " + spawn.getLocx() + " " + spawn.getLocy());
				}
			}
		}

		if (index == 0)
			activeChar.sendMessage("No current spawns found.");
	}

	public Scene getOwner() {
		return scn;
	}
}
